﻿namespace Hidistro.UI.Common.Controls
{
    using Hidistro.Entities;
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.IO;
    using System.Net;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Xml;

    public class RegionHandler : IHttpHandler
    {
        private void GetRegionInfo(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            int result = 0;
            int.TryParse(context.Request["regionId"], out result);
            if (result <= 0)
            {
                context.Response.Write("{\"Status\":\"0\"}");
            }
            else
            {
                XmlNode region = RegionHelper.GetRegion(result);
                if (region == null)
                {
                    context.Response.Write("{\"Status\":\"0\"}");
                }
                else
                {
                    int num2 = 1;
                    if (region.Name.Equals("city"))
                    {
                        num2 = 2;
                    }
                    else if (region.Name.Equals("county"))
                    {
                        num2 = 3;
                    }
                    string str = (num2 > 1) ? RegionHelper.GetFullPath(result) : "";
                    string str2 = "";
                    if (!region.Name.Equals("province"))
                    {
                        str2 = region.ParentNode.Attributes["id"].Value;
                    }
                    string s = "{";
                    s = (((((s + "\"Status\":\"OK\",") + "\"RegionId\":\"" + result.ToString(CultureInfo.InvariantCulture) + "\",") + "\"Depth\":\"" + num2.ToString(CultureInfo.InvariantCulture) + "\",") + "\"Path\":\"" + str + "\",") + "\"ParentId\":\"" + str2 + "\"") + "}";
                    context.Response.Write(s);
                }
            }
        }

        private static void GetRegions(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            int result = 0;
            int.TryParse(context.Request["parentId"], out result);
            XmlNode region = RegionHelper.GetRegion(result);
            //wnxd_RegionInfo region = RegionHelper.JSON_GetRegion(result);

            //int provinceId = -1;
            //int.TryParse(context.Request["provinceid"], out provinceId);
            //int cityId = -1;
            //int.TryParse(context.Request["cityid"], out cityId);
            if (region == null)
            {
                context.Response.Write("{\"Status\":\"0\"}");
            }
            else
            {
                Dictionary<int, string> citys;
                //if (cityId == -1)
                //{
                //    citys = RegionHelper.GetCitys(provinceId);
                //}
                //else
                //{
                //    citys = RegionHelper.GetCountys(provinceId, cityId);
                //}
                if (region.Name.Equals("province"))
                {
                    citys = RegionHelper.GetCitys(result);
                }
                else
                {
                    citys = RegionHelper.GetCountys(result);
                }
                if (citys.Count == 0)
                {
                    context.Response.Write("{\"Status\":\"0\"}");
                }
                else
                {
                    StringBuilder builder = new StringBuilder();
                    builder.Append("{");
                    builder.Append("\"Status\":\"OK\",");
                    builder.Append("\"Regions\":[");
                    foreach (int num2 in citys.Keys)
                    {
                        builder.Append("{");
                        builder.AppendFormat("\"RegionId\":\"{0}\",", num2.ToString(CultureInfo.InvariantCulture));
                        builder.AppendFormat("\"RegionName\":\"{0}\"", citys[num2]);
                        builder.Append("},");
                    }
                    builder.Remove(builder.Length - 1, 1);
                    builder.Append("]}");
                    citys.Clear();
                    context.Response.Write(builder.ToString());
                }
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                string str2 = context.Request["action"];
                if (str2 != null)
                {
                    if (!(str2 == "getregions"))
                    {
                        if (str2 == "getregioninfo")
                        {
                            goto Label_003A;
                        }
                        else if (str2 == "getzcode")
                        {
                            GetZcodeTo138ip(context);
                        }
                    }
                    else
                    {
                        GetRegions(context);
                    }
                }
                return;
            Label_003A:
                this.GetRegionInfo(context);
            }
            catch
            {
            }
        }

        private void GetZcodeTo138ip(HttpContext context)
        {
            string province = context.Request.Form["province"];
            string city = context.Request.Form["city"];
            string county = context.Request.Form["county"]; ;
            if (String.IsNullOrEmpty(county)) goto tmp;
            for (int i = 0; i < 3; i++)
            {
                if (i == 1)
                {
                    if (string.IsNullOrEmpty(city)) continue;
                    county = city;
                    city = null;
                }
                else if (i == 2)
                {
                    if (string.IsNullOrEmpty(province)) continue;
                    county = province;
                    province = null;
                }
                WebRequest request = WebRequest.Create(String.Format("http://wap.ip138.com/post_search.asp?area={0}&action=area2zip", county));
                WebResponse response = request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string html = reader.ReadToEnd();
                reader.Close();
                response.Close();
                Regex re = new Regex(string.Format(@"[{0}.*?\s+]?[{1}\s+]?{2}\s+邮编：(\d+)", string.IsNullOrEmpty(province) ? "" : province.Substring(0, 2), city, string.IsNullOrEmpty(province) ? county.Substring(0, 2) : county));
                Match mt = re.Match(html);
                if (mt.Success)
                {
                    context.Response.Write(mt.Groups[1]);
                    break;
                }
            }
        tmp:
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

